package cn.labbook.bluetooth.util.p645;


import lombok.Data;

@Data
public class BCD {
    private int codeByteNum;
    private byte[] codeBytes;
    private int decimalNum;
    private boolean isShow = true;
    private boolean hasNeg;

    public BCD() {
    }

    public BCD(int byteNum) {
        codeByteNum = byteNum;
        codeBytes = new byte[codeByteNum];
        for (int i = 0; i < codeByteNum; i++) codeBytes[i] = (byte) 0x00;
    }

    public BCD(byte[] codeBytes) {
        this.codeByteNum = codeBytes.length;
        this.codeBytes = codeBytes;
    }

    public int getCodeByteNum() {
        return codeByteNum;
    }

    public byte[] getCodeBytes() {
        return codeBytes;
    }

    public void setCodeBytes(byte[] bytes) {
        for (int i = 0; i < codeByteNum; i++) {
            codeBytes[i] = bytes[i];
        }
    }

    public String getBCDString() {
        return getBCDString(decimalNum);
    }

    public String getBCDString(int decimalNum) {
        String res = "";
        boolean neg = NumberUtil.isNeg(codeBytes[codeByteNum - 1]);
        for (int i = 0; i < codeByteNum; i++) {
            byte codeByte = codeBytes[i];
            String hexString;
            if (i == codeByteNum - 1) {
                if (neg && hasNeg && codeByte != -18) {
                    hexString = "-" + NumberUtil.toFullHexString((byte) ((codeByte & 0xff) - 128));
                } else {
                    hexString = NumberUtil.toFullHexString(codeByte);
                }
            } else {
                hexString = NumberUtil.toFullHexString(codeByte);
            }
            res = hexString + res;
        }//

        if (decimalNum > 0) {
            return res.substring(0, res.length() - decimalNum) + "." + res.substring(res.length() - decimalNum);
        }
        return res;
    }


    public void fromBCDString(String bcd) {
        for (int i = 0; i < codeByteNum; i++) {
            String strByte = bcd.substring(i * 2, i * 2 + 2);
            codeBytes[codeByteNum - 1 - i] = Integer.valueOf(strByte, 16).byteValue();
        }
    }
}
